home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / ZSI / twisted / wsgi.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-13  |  8.6 KB  |  271 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. import os
  5. import sys
  6. import types
  7. import inspect
  8. from StringIO import StringIO
  9. from zope.interface import classProvides, implements, Interface
  10. from ZSI import _get_element_nsuri_name, EvaluateException, ParseException, fault, ParsedSoap, SoapWriter
  11. from ZSI.twisted.reverse import DataHandler, ReverseHandlerChain, HandlerChainInterface
  12.  
  13. def soapmethod(requesttypecode, responsetypecode, soapaction = '', operation = None, **kw):
  14.     
  15.     def _closure(func_cb):
  16.         func_cb.root = (requesttypecode.nspname, requesttypecode.pname)
  17.         func_cb.action = soapaction
  18.         func_cb.requesttypecode = requesttypecode
  19.         func_cb.responsetypecode = responsetypecode
  20.         func_cb.soapmethod = True
  21.         func_cb.operation = None
  22.         return func_cb
  23.  
  24.     return _closure
  25.  
  26.  
  27. class SOAPCallbackHandler:
  28.     classProvides(HandlerChainInterface)
  29.     writerClass = None
  30.     
  31.     def processRequest(cls, ps, **kw):
  32.         resource = kw['resource']
  33.         request = kw['request']
  34.         root = _get_element_nsuri_name(ps.body_root)
  35.         for key, method in inspect.getmembers(resource, inspect.ismethod):
  36.             if getattr(method, 'soapmethod', False) and method.root == root:
  37.                 break
  38.                 continue
  39.         else:
  40.             raise RuntimeError, 'Missing soap callback method for root "%s"' % root
  41.         
  42.         try:
  43.             req = ps.Parse(method.requesttypecode)
  44.         except Exception:
  45.             ex = None
  46.             raise 
  47.  
  48.         
  49.         try:
  50.             rsp = method.responsetypecode.pyclass()
  51.         except Exception:
  52.             ex = None
  53.             raise 
  54.  
  55.         
  56.         try:
  57.             (req, rsp) = method(req, rsp)
  58.         except Exception:
  59.             ex = None
  60.             raise 
  61.  
  62.         return rsp
  63.  
  64.     processRequest = classmethod(processRequest)
  65.     
  66.     def processResponse(cls, output, **kw):
  67.         sw = SoapWriter(outputclass = cls.writerClass)
  68.         sw.serialize(output)
  69.         return sw
  70.  
  71.     processResponse = classmethod(processResponse)
  72.  
  73.  
  74. class SOAPHandlerChainFactory:
  75.     protocol = ReverseHandlerChain
  76.     
  77.     def newInstance(cls):
  78.         return cls.protocol(DataHandler, SOAPCallbackHandler)
  79.  
  80.     newInstance = classmethod(newInstance)
  81.  
  82.  
  83. class WSGIApplication(dict):
  84.     encoding = 'UTF-8'
  85.     
  86.     def __call__(self, env, start_response):
  87.         script = env['SCRIPT_NAME']
  88.         ipath = os.path.split(env['PATH_INFO'])[1:]
  89.         for i in range(1, len(ipath) + 1):
  90.             path = os.path.join(*ipath[:i])
  91.             print 'PATH: ', path
  92.             application = self.get(path)
  93.             if application is not None:
  94.                 env['SCRIPT_NAME'] = script + path
  95.                 env['PATH_INFO'] = ''
  96.                 print 'SCRIPT: ', env['SCRIPT_NAME']
  97.                 return application(env, start_response)
  98.                 continue
  99.         
  100.         return self._request_cb(env, start_response)
  101.  
  102.     
  103.     def _request_cb(self, env, start_response):
  104.         start_response('404 ERROR', [
  105.             ('Content-Type', 'text/plain')])
  106.         return [
  107.             'Move along people, there is nothing to see to hear']
  108.  
  109.     
  110.     def putChild(self, path, resource):
  111.         path = path.split('/')
  112.         lp = len(path)
  113.         if lp == 0:
  114.             raise RuntimeError, 'bad path "%s"' % path
  115.         
  116.         if lp == 1:
  117.             self[path[0]] = resource
  118.         
  119.         for i in range(len(path)):
  120.             if not path[i]:
  121.                 continue
  122.             
  123.         
  124.         next = self.get(path[i], None)
  125.         if next is None:
  126.             next = self[path[i]] = WSGIApplication()
  127.         
  128.         next.putChild('/'.join(path[-1:]), resource)
  129.  
  130.  
  131.  
  132. class SOAPApplication(WSGIApplication):
  133.     factory = SOAPHandlerChainFactory
  134.     
  135.     def __init__(self, **kw):
  136.         dict.__init__(self, **kw)
  137.         self.delegate = None
  138.  
  139.     
  140.     def _request_cb(self, env, start_response):
  141.         if env['REQUEST_METHOD'] == 'GET':
  142.             return self._handle_GET(env, start_response)
  143.         
  144.         if env['REQUEST_METHOD'] == 'POST':
  145.             return self._handle_POST(env, start_response)
  146.         
  147.         start_response('500 ERROR', [
  148.             ('Content-Type', 'text/plain')])
  149.         s = StringIO()
  150.         h = env.items()
  151.         h.sort()
  152.         for k, v in h:
  153.             print >>s, k, '=', `v`
  154.         
  155.         return [
  156.             s.getvalue()]
  157.  
  158.     
  159.     def _handle_GET(self, env, start_response):
  160.         if env['QUERY_STRING'].lower() == 'wsdl':
  161.             start_response('200 OK', [
  162.                 ('Content-Type', 'text/plain')])
  163.             if not self.delegate:
  164.                 pass
  165.             r = self
  166.             return _resourceToWSDL(r)
  167.         
  168.         start_response('404 ERROR', [
  169.             ('Content-Type', 'text/plain')])
  170.         return [
  171.             'NO RESOURCE FOR GET']
  172.  
  173.     
  174.     def _handle_POST(self, env, start_response):
  175.         input = env['wsgi.input']
  176.         data = input.read(int(env['CONTENT_LENGTH']))
  177.         mimeType = 'text/xml'
  178.         if self.encoding is not None:
  179.             mimeType = 'text/xml; charset="%s"' % self.encoding
  180.         
  181.         request = None
  182.         if not self.delegate:
  183.             pass
  184.         resource = self
  185.         chain = self.factory.newInstance()
  186.         
  187.         try:
  188.             pyobj = chain.processRequest(data, request = request, resource = resource)
  189.         except Exception:
  190.             ex = None
  191.             start_response('500 ERROR', [
  192.                 ('Content-Type', mimeType)])
  193.             return [
  194.                 fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
  195.  
  196.         
  197.         try:
  198.             soap = chain.processResponse(pyobj, request = request, resource = resource)
  199.         except Exception:
  200.             ex = None
  201.             start_response('500 ERROR', [
  202.                 ('Content-Type', mimeType)])
  203.             return [
  204.                 fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
  205.  
  206.         start_response('200 OK', [
  207.             ('Content-Type', mimeType)])
  208.         return [
  209.             soap]
  210.  
  211.  
  212.  
  213. def test(app, port = 8080, host = 'localhost'):
  214.     reactor = reactor
  215.     import twisted.internet
  216.     log = log
  217.     import twisted.python
  218.     HTTPFactory = HTTPFactory
  219.     import twisted.web2.channel
  220.     Site = Site
  221.     import twisted.web2.server
  222.     WSGIResource = WSGIResource
  223.     import twisted.web2.wsgi
  224.     log.startLogging(sys.stdout)
  225.     reactor.listenTCP(port, HTTPFactory(Site(WSGIResource(app))), interface = host)
  226.     reactor.run()
  227.  
  228.  
  229. def _issoapmethod(f):
  230.     if type(f) is types.MethodType:
  231.         pass
  232.     return getattr(f, 'soapmethod', False)
  233.  
  234.  
  235. def _resourceToWSDL(resource):
  236.     ElementTree = ElementTree
  237.     import xml.etree
  238.     Element = Element
  239.     QName = QName
  240.     import xml.etree.ElementTree
  241.     WSDL = WSDL
  242.     import ZSI.wstools.Namespaces
  243.     r = resource
  244.     methods = filter(_issoapmethod, (map,)((lambda i: getattr(r, i)), dir(r)))
  245.     tns = ''
  246.     defs = Element('{%s}definitions' % WSDL.BASE)
  247.     defs.attrib['name'] = 'SampleDefs'
  248.     defs.attrib['targetNamespace'] = tns
  249.     porttype = Element('{%s}portType' % WSDL)
  250.     porttype.attrib['name'] = QName('{%s}SamplePortType' % tns)
  251.     binding = Element('{%s}binding' % WSDL)
  252.     defs.append(binding)
  253.     binding.attrib['name'] = QName('{%s}SampleBinding' % tns)
  254.     binding.attrib['type'] = porttype.get('name')
  255.     for m in methods:
  256.         m.action
  257.     
  258.     service = Element('{%s}service' % WSDL.BASE)
  259.     defs.append(service)
  260.     service.attrib['name'] = 'SampleService'
  261.     port = Element('{%s}port' % WSDL.BASE)
  262.     service.append(port)
  263.     port.attrib['name'] = 'SamplePort'
  264.     port.attrib['binding'] = binding.get('name')
  265.     soapaddress = Element('{%s}address' % WSDL.BIND_SOAP)
  266.     soapaddress.attrib['location'] = 'http://localhost/bla'
  267.     port.append(soapaddress)
  268.     return [
  269.         ElementTree.tostring(defs)]
  270.  
  271.